package com.zcxk.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zcxk.config.AuthToken;
import com.zcxk.constant.Constants;
import com.zcxk.dao.dataobject.User;
import com.zcxk.dao.mapper.SqlSession;
import com.zcxk.dao.mapper.UserMapper;
import com.zcxk.dto.UserDTO;
import com.zcxk.enums.ErrorCodeEnum;
import com.zcxk.exception.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Objects;

/**
 * @author wangping
 * @date 2022-09-12 15:58
 */
public class UserServiceImpl implements UserService {

  private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

	@Override
	public UserDTO login(User userDto) {
		QueryWrapper<User> wrapper = new QueryWrapper<>();
    System.out.println(DigestUtil.md5Hex(userDto.getPassword()));
		wrapper.eq("username", userDto.getUsername())
						.eq("password", DigestUtil.md5Hex(userDto.getPassword()));
    UserMapper userMapper = SqlSession.getSession().getMapper(UserMapper.class);
    User user = userMapper.selectOne(wrapper);
		if (Objects.nonNull(user)){
			Long uid = user.getUid();
			UserDTO userDTO = new UserDTO();
			BeanUtil.copyProperties(user, userDTO);

      // 一天过期
      AuthToken token = new AuthToken(uid, System.currentTimeMillis() + 60_000 * 60 * 24);
			userDTO.setToken(token.toSecureString(Constants.getSecretKey()));
			return userDTO;
		}
    logger.warn("user not found, user: {}", userDto.getUsername());
		throw new ServiceException(ErrorCodeEnum.USER_NOT_FIND);
	}

  public static void main(String[] args) {
    System.out.println(DigestUtil.md5Hex("password"));
  }
}
